package cn.ivast.action;

import cn.ivast.entity.Article;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@WebServlet(value = {"/article"})
public class ArticleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        System.out.println(req.getParameter("title"));
        System.out.println(req.getParameter("content"));
        Configuration cfg=new Configuration(Configuration.VERSION_2_3_22);
        String templatePath=this.getClass().getClassLoader().getResource("/templates").getPath();
        cfg.setDirectoryForTemplateLoading(new File(templatePath));
        cfg.setDefaultEncoding("UTF-8");
        Article article = new Article();
        article.setId(321654);
        article.setTitle(req.getParameter("title"));
        article.setContent(req.getParameter("content"));
        File fileDir = new File(req.getServletContext().getRealPath("/article/"));
        if (!fileDir.exists()){
            fileDir.mkdir();
        }
        try {
            Template template = cfg.getTemplate("article.ftl");
            File file=new File(req.getServletContext().getRealPath("/article/"+article.getId()+".html"));
            Writer writer = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
            Map<String, Object> articleData = new HashMap<String, Object>();
            articleData.put("article", article);
            template.process(articleData,writer);
            writer.flush();
            writer.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
